// statsMixin.js
import * as echarts from 'echarts';
import { ref, onMounted, onUnmounted } from 'vue';

export const statsMixin = {
    setup() {
        const companyCountChart = ref(null);
        const employeeCountChart = ref(null);
        const capitalChart = ref(null);
        const highTechChart = ref(null);
        const statsData = ref(null);
        const isFullscreen = ref(false);
        const loading = ref(false);

        // 图表实例对象
        let companyCountChartInstance = null;
        let employeeCountChartInstance = null;
        let capitalChartInstance = null;
        let highTechChartInstance = null;

        const renderStatsCharts = () => {
            if (!statsData.value) return;
            
            console.log('区域企业统计数据:', statsData.value);
            
            // 数据预处理，兼容不同的字段名
            const normalizedData = statsData.value.map(item => {
                // 创建一个新对象，防止修改原始数据
                const normalizedItem = { ...item };
                
                // 处理省份字段
                if (!normalizedItem.province && (normalizedItem.provinceName || normalizedItem.region || normalizedItem.area)) {
                    normalizedItem.province = normalizedItem.provinceName || normalizedItem.region || normalizedItem.area;
                }
                
                // 处理企业数量字段
                if (normalizedItem.companyCount === undefined && normalizedItem.count !== undefined) {
                    normalizedItem.companyCount = normalizedItem.count;
                }
                
                // 处理员工数量字段
                if (normalizedItem.employeeCount === undefined && normalizedItem.totalEmployees !== undefined) {
                    normalizedItem.employeeCount = normalizedItem.totalEmployees;
                }
                
                // 处理注册资本字段
                if (normalizedItem.registeredCapital === undefined && normalizedItem.totalCapital !== undefined) {
                    normalizedItem.registeredCapital = normalizedItem.totalCapital;
                }
                
                // 处理高新企业数量字段
                if (normalizedItem.highTechCount === undefined && normalizedItem.hightech_count !== undefined) {
                    normalizedItem.highTechCount = normalizedItem.hightech_count;
                }
                
                // 处理高新企业比率字段
                if (normalizedItem.highTechRatio === undefined) {
                    if (normalizedItem.hightech_ratio !== undefined) {
                        normalizedItem.highTechRatio = normalizedItem.hightech_ratio;
                    } else if (normalizedItem.companyCount > 0 && normalizedItem.highTechCount !== undefined) {
                        normalizedItem.highTechRatio = normalizedItem.highTechCount / normalizedItem.companyCount;
                    }
                }
                
                return normalizedItem;
            });
            
            console.log('数据字段标准化后:', normalizedData);
            
            // 初始化企业数量图表
            if (companyCountChart.value) {
                try {
                    // 销毁之前的实例
                    if (companyCountChartInstance) {
                        companyCountChartInstance.dispose();
                    }
                    
                    companyCountChartInstance = echarts.init(companyCountChart.value);

                    // 按企业数量排序取前15个
                    const sortedData = [...normalizedData].sort((a, b) => b.companyCount - a.companyCount).slice(0, 15);
                    const provinces = sortedData.map(item => item.province);
                    const counts = sortedData.map(item => item.companyCount);

                    companyCountChartInstance.setOption({
                        title: {
                            text: '各省企业数量统计',
                            left: 'center',
                            top: 5,
                            textStyle: { fontSize: 14 }
                        },
                        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                        grid: { left: '3%', right: '4%', bottom: '10%', top: '20%', containLabel: true },
                        xAxis: { type: 'category', data: provinces, axisLabel: { interval: 0, rotate: 45, fontSize: 10 } },
                        yAxis: { type: 'value', axisLabel: { fontSize: 10 } },
                        series: [{ 
                            data: counts, 
                            type: 'bar', 
                            showBackground: true, 
                            backgroundStyle: { color: 'rgba(180, 180, 180, 0.2)' },
                            itemStyle: {
                                color: function(params) {
                                    const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
                                    return colors[params.dataIndex % colors.length];
                                }
                            }
                        }]
                    });
                } catch (error) {
                    console.error('渲染企业数量图表失败:', error);
                }
            }

            // 初始化员工数量图表
            if (employeeCountChart.value) {
                try {
                    // 销毁之前的实例
                    if (employeeCountChartInstance) {
                        employeeCountChartInstance.dispose();
                    }
                    
                    employeeCountChartInstance = echarts.init(employeeCountChart.value);

                    // 按员工数量排序取前15个
                    const sortedData = [...normalizedData].sort((a, b) => b.employeeCount - a.employeeCount).slice(0, 15);
                    const provinces = sortedData.map(item => item.province);
                    const counts = sortedData.map(item => item.employeeCount);

                    employeeCountChartInstance.setOption({
                        title: {
                            text: '各省员工数量统计',
                            left: 'center',
                            top: 5,
                            textStyle: { fontSize: 14 }
                        },
                        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                        grid: { left: '3%', right: '4%', bottom: '10%', top: '20%', containLabel: true },
                        xAxis: { type: 'category', data: provinces, axisLabel: { interval: 0, rotate: 45, fontSize: 10 } },
                        yAxis: { type: 'value', axisLabel: { fontSize: 10 } },
                        series: [{ 
                            data: counts, 
                            type: 'bar', 
                            showBackground: true, 
                            backgroundStyle: { color: 'rgba(180, 180, 180, 0.2)' },
                            itemStyle: {
                                color: function(params) {
                                    const colors = ['#73c0de', '#5470c6', '#91cc75', '#fac858', '#ee6666', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
                                    return colors[params.dataIndex % colors.length];
                                }
                            }
                        }]
                    });
                } catch (error) {
                    console.error('渲染员工数量图表失败:', error);
                }
            }

            // 初始化注册资本图表
            if (capitalChart.value) {
                try {
                    // 销毁之前的实例
                    if (capitalChartInstance) {
                        capitalChartInstance.dispose();
                    }
                    
                    capitalChartInstance = echarts.init(capitalChart.value);

                    // 格式化注册资本数据
                    const formatCapital = (capital) => {
                        if (!capital || isNaN(Number(capital))) return 0;
                        // 将科学计数法转换为普通数字
                        const num = parseFloat(capital);
                        // 直接使用数值，不需要除以10000（数据中已经是万元单位）
                        return parseFloat(num.toFixed(2)); 
                    };

                    // 使用registeredCapital字段
                    // 按注册资本排序取前8个用于饼图
                    const filteredData = normalizedData
                        .filter(item => item.province && item.registeredCapital > 10000) // 只显示注册资本较大的省份
                        .sort((a, b) => b.registeredCapital - a.registeredCapital)
                        .slice(0, 8) // 只取前8个，避免饼图过于拥挤
                        .map(item => ({
                            name: item.province,
                            value: formatCapital(item.registeredCapital)
                        }));

                    // 如果还有其他省份，合并为"其他"
                    const otherProvinces = normalizedData
                        .filter(item => item.province && item.registeredCapital > 0)
                        .sort((a, b) => b.registeredCapital - a.registeredCapital)
                        .slice(8); // 第8个之后的省份
                        
                    if (otherProvinces.length > 0) {
                        const otherSum = otherProvinces.reduce((sum, item) => sum + parseFloat(item.registeredCapital || 0), 0);
                        if (otherSum > 0) {
                            filteredData.push({
                                name: '其他省份',
                                value: parseFloat(otherSum.toFixed(2))
                            });
                        }
                    }

                    console.log('注册资本数据处理后:', filteredData);

                    capitalChartInstance.setOption({
                        title: {
                            text: '各省注册资本统计(万元)',
                            left: 'center',
                            top: 5,
                            textStyle: { fontSize: 14 }
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{b}: {c} 万元 ({d}%)'
                        },
                        legend: {
                            orient: 'horizontal',
                            bottom: 0,
                            left: 'center',
                            type: 'scroll',
                            pageButtonItemGap: 5,
                            pageButtonGap: 5,
                            pageIconSize: 10,
                            pageTextStyle: {
                                fontSize: 10
                            },
                            textStyle: {
                                fontSize: 10
                            }
                        },
                        series: [
                            {
                                name: '注册资本',
                                type: 'pie',
                                radius: ['20%', '60%'],
                                center: ['50%', '45%'],
                                avoidLabelOverlap: true,
                                itemStyle: {
                                    borderRadius: 2,
                                    borderColor: '#fff',
                                    borderWidth: 1
                                },
                                label: {
                                    fontSize: 10,
                                    formatter: '{b}\n{d}%',
                                    position: 'outside'
                                },
                                labelLine: {
                                    show: true,
                                    length: 10,
                                    length2: 6
                                },
                                data: filteredData,
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    });
                } catch (error) {
                    console.error('渲染注册资本图表失败:', error);
                }
            }

            // 初始化高新企业图表
            if (highTechChart.value) {
                try {
                    // 销毁之前的实例
                    if (highTechChartInstance) {
                        highTechChartInstance.dispose();
                    }
                    
                    highTechChartInstance = echarts.init(highTechChart.value);

                    // 按高新企业比例排序取前10个
                    const sortedData = [...normalizedData]
                        .filter(item => item.highTechCount > 0 && item.companyCount > 0) // 确保有有效数据
                        .sort((a, b) => (b.highTechRatio || 0) - (a.highTechRatio || 0))
                        .slice(0, 10);
                    
                    const provinces = sortedData.map(item => item.province);
                    const highTechRatios = sortedData.map(item => parseFloat((item.highTechRatio * 100).toFixed(2)));
                    const highTechCounts = sortedData.map(item => item.highTechCount);

                    highTechChartInstance.setOption({
                        title: {
                            text: '各省高新企业统计',
                            left: 'center',
                            top: 5,
                            textStyle: { fontSize: 14 }
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { type: 'shadow' },
                            formatter: function(params) {
                                const ratioParam = params[0];
                                const countParam = params[1];
                                return ratioParam.name + '<br/>' +
                                    ratioParam.seriesName + ': ' + ratioParam.value + '%<br/>' +
                                    countParam.seriesName + ': ' + countParam.value;
                            }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '10%',
                            top: '20%',
                            containLabel: true
                        },
                        legend: {
                            data: ['高新企业比例(%)', '高新企业数量'],
                            bottom: 0,
                            textStyle: { fontSize: 10 }
                        },
                        xAxis: {
                            type: 'category',
                            data: provinces,
                            axisLabel: { interval: 0, rotate: 45, fontSize: 10 }
                        },
                        yAxis: [
                            {
                                type: 'value',
                                name: '比例',
                                min: 0,
                                max: 100,
                                interval: 20,
                                axisLabel: {
                                    formatter: '{value}%',
                                    fontSize: 10
                                }
                            },
                            {
                                type: 'value',
                                name: '数量',
                                axisLabel: { fontSize: 10 }
                            }
                        ],
                        series: [
                            {
                                name: '高新企业比例(%)',
                                type: 'bar',
                                data: highTechRatios,
                                itemStyle: {
                                    color: '#5470c6'
                                }
                            },
                            {
                                name: '高新企业数量',
                                type: 'line',
                                yAxisIndex: 1,
                                data: highTechCounts,
                                itemStyle: {
                                    color: '#91cc75'
                                },
                                symbol: 'circle',
                                symbolSize: 6,
                                lineStyle: {
                                    width: 2
                                }
                            }
                        ]
                    });
                } catch (error) {
                    console.error('渲染高新企业图表失败:', error);
                }
            }
        };

        // 全屏变化事件处理函数
        const handleFullscreenChange = () => {
            // 检查当前是否有元素处于全屏状态
            const isCurrentlyFullscreen = !!document.fullscreenElement || 
                                       !!document.webkitFullscreenElement || 
                                       !!document.mozFullScreenElement || 
                                       !!document.msFullscreenElement;
            
            // 更新状态并重新渲染图表
            if (isFullscreen.value !== isCurrentlyFullscreen) {
                console.log('[StatsMixin] 全屏状态变化:', isCurrentlyFullscreen);
                isFullscreen.value = isCurrentlyFullscreen;
                
                // 调整图表大小
                setTimeout(() => {
                    if (companyCountChartInstance) companyCountChartInstance.resize();
                    if (employeeCountChartInstance) employeeCountChartInstance.resize();
                    if (capitalChartInstance) capitalChartInstance.resize();
                    if (highTechChartInstance) highTechChartInstance.resize();
                }, 300);
            }
        };
        
        // 需要添加toggleFullscreen函数以供StatsOverview组件使用
        const toggleFullscreen = () => {
            const graphCard = document.querySelector('.graph-card');
            if (!graphCard) {
                console.error('未找到图表容器元素');
                return;
            }
            
            if (!isFullscreen.value) {
                try {
                    // 在进入全屏前强制设置整个页面背景
                    document.documentElement.style.backgroundColor = 'white';
                    document.body.style.backgroundColor = 'white';
                    
                    // 设置容器背景色为白色
                    graphCard.style.backgroundColor = 'white';
                    graphCard.style.background = 'white';
                    
                    // 设置内部图表元素背景色
                    graphCard.querySelectorAll('.chart, .chart-wrapper').forEach(el => {
                        el.style.backgroundColor = 'white';
                        el.style.background = 'white';
                    });
                    
                    // 创建并应用全屏样式表
                    const styleElement = document.createElement('style');
                    styleElement.id = 'fullscreen-fix-style';
                    styleElement.textContent = `
                        :fullscreen, :-webkit-full-screen, :-moz-full-screen, :-ms-fullscreen {
                            background-color: white !important;
                            background: white !important;
                        }
                        ::backdrop, ::-webkit-backdrop {
                            background-color: white !important;
                            background: white !important;
                        }
                    `;
                    document.head.appendChild(styleElement);
                    
                    if (graphCard.requestFullscreen) {
                        graphCard.requestFullscreen();
                    } else if (graphCard.mozRequestFullScreen) {
                        graphCard.mozRequestFullScreen();
                    } else if (graphCard.webkitRequestFullscreen) {
                        graphCard.webkitRequestFullscreen();
                    } else if (graphCard.msRequestFullscreen) {
                        graphCard.msRequestFullscreen();
                    }
                    isFullscreen.value = true;
                } catch (error) {
                    console.error('进入全屏模式失败:', error);
                }
            } else {
                try {
                    // 移除全屏样式表
                    const styleElement = document.getElementById('fullscreen-fix-style');
                    if (styleElement) {
                        document.head.removeChild(styleElement);
                    }
                    
                    // 添加安全检查 - 确保document仍然处于活动状态且有fullscreenElement
                    if (!document.fullscreenElement && 
                        !document.webkitFullscreenElement && 
                        !document.mozFullScreenElement && 
                        !document.msFullscreenElement) {
                        console.log('当前没有元素处于全屏状态，直接更新状态');
                        isFullscreen.value = false;
                        return;
                    }
                    
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitExitFullscreen) {
                        document.webkitExitFullscreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    isFullscreen.value = false;
                } catch (error) {
                    console.error('退出全屏模式失败:', error);
                    // 如果退出全屏失败，强制更新状态
                    isFullscreen.value = false;
                }
            }
            
            // 调整图表大小
            setTimeout(() => {
                if (companyCountChartInstance) companyCountChartInstance.resize();
                if (employeeCountChartInstance) employeeCountChartInstance.resize();
                if (capitalChartInstance) capitalChartInstance.resize();
                if (highTechChartInstance) highTechChartInstance.resize();
            }, 300);
        };
        
        onMounted(() => {
            // 添加全屏变化事件监听
            document.addEventListener('fullscreenchange', handleFullscreenChange);
            document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
            document.addEventListener('mozfullscreenchange', handleFullscreenChange);
            document.addEventListener('MSFullscreenChange', handleFullscreenChange);
        });
        
        onUnmounted(() => {
            // 移除全屏变化事件监听
            document.removeEventListener('fullscreenchange', handleFullscreenChange);
            document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
            document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
            document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
            
            // 销毁图表实例
            if (companyCountChartInstance) companyCountChartInstance.dispose();
            if (employeeCountChartInstance) employeeCountChartInstance.dispose();
            if (capitalChartInstance) capitalChartInstance.dispose();
            if (highTechChartInstance) highTechChartInstance.dispose();
        });

        return {
            companyCountChart,
            employeeCountChart,
            capitalChart,
            highTechChart,
            statsData,
            isFullscreen,
            loading,
            renderStatsCharts,
            toggleFullscreen
        };
    }
};